package com.mayi.api.http;

import java.net.URI;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;

/**
 * 
 * @title HttpHelper
 * @description Http请求帮助类
 * @author yacong_liu Email:2682505646@qq.com
 * @date 2019年12月30日
 */
public class HttpHelper {
    private final static String UTF8 = "UTF-8";

    public static String post(Map<String, String> params, String url) throws Exception {
        return post(params, url, 0);
    }

    public static String post(Map<String, String> params, String url, int timeOutInMillis) throws Exception {
        return post(null, params, url, timeOutInMillis);
    }

    public static String post(Map<String, String> headers, Map<String, String> params, String url)
            throws Exception {
        return post(headers, params, url, 0);
    }

    public static String get(String url) throws Exception {
        return get(null, null, url, 0);
    }

    public static String get(String url, int timeOutInMillis) throws Exception {
        return get(null, null, url, timeOutInMillis);
    }

    public static String get(Map<String, String> params, String url) throws Exception {
        return get(null, params, url, 0);

    }

    public static String get(Map<String, String> params, String url, int timeOutInMillis) throws Exception {
        return get(null, params, url, timeOutInMillis);

    }

    public static String get(Map<String, String> headers, Map<String, String> params, String url)
            throws Exception {
        return get(headers, params, url, 0);
    }

    /**
     * POST
     * 
     * @param headers 请求头参数
     * @param params 参数
     * @param url URL
     * @param timeOutInMillis 请求超时时间
     * @return
     * @throws Exception
     */
    public static String post(Map<String, String> headers, Map<String, String> params, String url,
            int timeOutInMillis) throws Exception {
        HttpPost post = null;
        try {
            post = getHttpPost(headers, params, url, timeOutInMillis);
            return HttpClientHelper.getHttpClient().execute(post, UTF8);
        } finally {
            if (post != null)
                post.abort();
        }

    }

    /**
     * GET
     * 
     * @param headers 请求头参数
     * @param params 参数
     * @param url URL
     * @param timeOutInMillis 请求超时时间
     * @return
     * @throws Exception
     */
    public static String get(Map<String, String> headers, Map<String, String> params, String url,
            int timeOutInMillis) throws Exception {
        HttpGet get = null;
        try {
            get = getHttpGet(headers, params, url, timeOutInMillis);
            return HttpClientHelper.getHttpClient().execute(get, UTF8);
        } finally {
            if (get != null)
                get.abort();
        }

    }

    /**
     * 组装HttpPost
     * 
     * @param headers 请求头参数
     * @param params 参数
     * @param url URL
     * @param timeOutInMillis 请求超时时间
     * @return HttpPost
     * @throws Exception
     */
    private static HttpPost getHttpPost(Map<String, String> headers, Map<String, String> params, String url,
            int timeOutInMillis) throws Exception {
        HttpPost post = null;
        post = new HttpPost(url);
        if (headers != null) {
            Set<String> set = headers.keySet();
            Iterator<String> it = set.iterator();
            while (it.hasNext()) {
                String key = it.next();
                post.addHeader(key, headers.get(key));
            }
        }
        if (params != null) {
            List<NameValuePair> nvp = new LinkedList<NameValuePair>();
            Set<String> set = params.keySet();
            Iterator<String> it = set.iterator();
            while (it.hasNext()) {
                String key = it.next();
                nvp.add(new BasicNameValuePair(key, params.get(key)));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvp, UTF8);
            post.setEntity(entity);
        }
        if (timeOutInMillis > 0) {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOutInMillis)
                    .setConnectTimeout(timeOutInMillis).build();
            post.setConfig(requestConfig);
        }
        return post;
    }

    /**
     * POST
     * 
     * @param headers 请求头参数
     * @param jsonObject 请求参数
     * @param url URL
     * @param timeOutInMillis 请求超时时间
     * @return
     * @throws Exception
     */
    public static String post(Map<String, String> headers, String jsonObject, String url, int timeOutInMillis)
            throws Exception {
        HttpPost post = null;
        try {
            post = new HttpPost(url);
            if (headers != null) {
                Set<String> set = headers.keySet();
                Iterator<String> it = set.iterator();
                while (it.hasNext()) {
                    String key = it.next();
                    post.addHeader(key, headers.get(key));
                }
            }

            if (null == jsonObject || jsonObject.isEmpty()) {
                throw new Exception("json参数为空！");
            }

            StringEntity entity = new StringEntity(jsonObject, UTF8);
            if (timeOutInMillis > 0) {
                RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOutInMillis)
                        .setConnectTimeout(timeOutInMillis).build();
                post.setConfig(requestConfig);
            }
            post.setEntity(entity);
            return HttpClientHelper.getHttpClient().execute(post, UTF8);
        } finally {
            if (post != null)
                post.abort();
        }
    }

    /**
     * 组装HttpGet
     * 
     * @param headers 请求头参数
     * @param params 参数
     * @param url URL
     * @param timeOutInMillis 超时时间
     * @return HttpGet
     * @throws Exception
     */
    private static HttpGet getHttpGet(Map<String, String> headers, Map<String, String> params, String url,
            int timeOutInMillis) throws Exception {
        HttpGet get = null;
        get = new HttpGet(url);
        if (headers != null) {
            Set<String> set = headers.keySet();
            Iterator<String> it = set.iterator();
            while (it.hasNext()) {
                String key = it.next();
                get.addHeader(key, headers.get(key));
            }
        }

        if (params != null) {
            List<NameValuePair> nvp = new LinkedList<NameValuePair>();
            Set<Map.Entry<String, String>> set = params.entrySet();
            for (Map.Entry<String, String> entry : set) {
                nvp.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            String param = URLEncodedUtils.format(nvp, UTF8);
            get.setURI(URI.create(url + "?" + param));

        }

        if (timeOutInMillis > 0) {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOutInMillis)
                    .setConnectTimeout(timeOutInMillis).build();
            get.setConfig(requestConfig);
        }

        return get;
    }

}
